import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'


import Table from 'antd/lib/table'
import Button from 'antd/lib/button'

import Navbar from '../../../Component/navbar'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Modal from 'antd/lib/modal'
import Radio from 'antd/lib/radio'
import Popconfirm from 'antd/lib/popconfirm'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const { TextArea } = Input;
const RadioGroup = Radio.Group;

let oper = null;

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
            allAccount: [],
            status:[],
            showAddModal: false,
            app:[],
            industry:[]
        }
    }
    componentDidMount() {
        this.getSelect();
    }
   async getSelect() {
        await Com.getSelection.call(this, 'SmsUserTempleteStatusEnum', 'status');
        await Com.getSelection.call(this, 'SmsUserSignApplicationEnum', 'app', false);
        await Com.getSelection.call(this, 'SmsUserSignIndustryEnum', 'industry',false);
        axios.post(Api['getAllUserAccount']).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                this.setState({
                    allAccount: data
                }, () => { this.search(); })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            account:this.accountInput.input.value,
            sign: this.signInput.input.value,
            status: this.statusInput.rcSelect.state.value[0],
            defauls: this.deInput.rcSelect.state.value[0],
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj, this.state.allAccount);
    }
    showAddModal() {
        this.setState({
            showAddModal: true
        }, () => {
            this.props.form.setFieldsValue({
                account: this.state.allAccount[0],
                application: this.state.app[0].index,
                industry: this.state.industry[0].index,
            })
        })
    }
    handleCancel() {
        this.setState({
            showAddModal: false
        })
    }
    handleSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['addSign'], data).then(res => {
                    if (res) {
                        this.search();
                        this.props.form.resetFields()
                        message.success('提交成功')
                        this.setState({
                            showAddModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <Navbar ref={(item) => {oper=item}}>
                <Form layout="inline">
                    <FormItem label="账号"><Input style={{ width: '150px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="签名"><Input style={{ width: '150px' }} ref={(input) => { this.signInput = input }} /></FormItem>
                    <FormItem label="是否默认">
                        <Select defaultValue='' style={{ width: '150px' }} ref={(input) => { this.deInput = input }}>
                            <Option value=''>全部</Option>
                            <Option value={1}>默认</Option>
                            <Option value={0}>非默认</Option>
                        </Select>
                    </FormItem>                    
                    <FormItem label="状态">
                    <Select defaultValue='' style={{ width: '150px' }} ref={(input) => { this.statusInput = input }}>
                        {this.state.status.map((item, index) => {
                            return <Option key={index} value={item.index}>{item.desc}</Option>
                        })}
                    </Select>
                    </FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="plus" onClick={this.showAddModal.bind(this)}>添加</Button>
                    </FormItem>
                </Form>
                <Modal visible={this.state.showAddModal} onCancel={this.handleCancel.bind(this)} title="新增" footer={[
                    <Button key="sure" type="primary" onClick={this.handleSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="账号" {...formItemLayout}>
                            {getFieldDecorator('account')(<Select style={{ width: 150 }}>
                                {this.state.allAccount.map((item, index) => { return <Option key={index} value={item}>{item}</Option> })}
                            </Select>
                            )}
                        </FormItem> 
                        <FormItem label="签名" {...formItemLayout}>
                            {getFieldDecorator('sign',{ validateFirst: true, rules: [{ required: true, message: '请输入签名' }, { max: 50, message: '50位以内' }]})(<Input style={{ width: 250 }} />)}
                        </FormItem>
                        <FormItem label="设为默认" {...formItemLayout}>
                            {getFieldDecorator('defauls',{initialValue:0})(
                                <RadioGroup>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                              </RadioGroup>
                            )}
                        </FormItem>
                        <FormItem label="应用场景" {...formItemLayout}>
                            {getFieldDecorator('application')(<Select style={{ width: 150 }}>
                                {this.state.app.map((item, index) => { return <Option key={item.index} value={item.index}>{item.desc}</Option> })}
                            </Select>
                            )}
                        </FormItem>
                        <FormItem label="行业" {...formItemLayout}>
                            {getFieldDecorator('industry')(<Select style={{ width: 150 }}>
                                {this.state.industry.map((item, index) => { return <Option key={item.index} value={item.index}>{item.desc}</Option> })}
                            </Select>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            showEditModal: false,
            nowRow: null,
            currentPage: 1,
            allAccount: [],
        }
    }
    async componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            currntPage: nextprops.currentPage,
            allAccount: nextprops.allAccount
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    deleteRow(record) {
        this.props.deleteRow(record)
    }
    showEdit(record) {
        this.setState({
            nowRow: record,
            showEditModal: true
        })
        this.props.form.setFieldsInitialValue({
            account: record.account,
            template: record.template
        })
    }
    handleCancel() {
        this.setState({
            showEditModal: false
        })
    }
    handleSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values));
                data.id = this.state.nowRow.id;
                data.status = 3;
                axios.post(Api['updateSign'], data).then(res => {
                    if (res) {
                        this.props.search();
                        this.props.form.resetFields()
                        message.success('操作成功')
                        this.setState({
                            showEditModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    pass(record){
        const that = this;
        confirm({
            title: '通过',
            content: '您确定要通过吗？',
            okText: '通过',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                const data = {};
                data.id = record.id;
                data.status = 2;
                axios.post(Api['updateSign'], data).then(res => {
                    if (res) {
                        that.props.search();
                        message.success('操作成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })     
            },
            onCancel() { },
        });
    }
    setDefault(record){
        const that = this;
        confirm({
            title: '默认',
            content: '您确定要设为默认吗？',
            okText: '设为默认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['updateSignDefault']+`?id=${record.id}`).then(res => {
                    if (res) {
                        that.props.search();
                        message.success('操作成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })     
            },
            onCancel() { },
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const columns = [
            { title: '账号', dataIndex: 'account', key: '0', width: 220 },
            { title: '签名', dataIndex: 'sign', key: '1', width: 220 },
            { title: '行业', dataIndex: 'industryName', key: '2', width: 220 },
            { title: '应用场景', dataIndex: 'appName', key: '3', width: 220 },
            { title: '状态', key: '4', width: 120 ,render: (record) => {
                    return (
                       record.status === 1?<span style={{color:'blue'}}>审核中</span>:(record.status === 2?<span style={{color:'green'}}>审核通过</span>:<span style={{color:'red'}}>审核驳回</span>)
                    )
                }
            },
            { title: '驳回原因', key: '5' ,render: (record) => {
                    return (
                            <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.reason}>
                                <a>{record.reasonAbb}</a>
                            </Popconfirm>
                        )
                }
            },
            { title: '审核时间', dataIndex: 'auditTime', key: '7', width: 200 },
            { title: '创建时间', dataIndex: 'createTime', key: '6', width: 200 },
            {
                title: '操作',
                key: '8',
                width: 300,
                fixed:'right',
                render: (record) => {
                    return (
                        <div>
                            {record.status === 2?(record.defauls?<span style={{color:'green'}}>已为默认</span>:<a onClick={this.setDefault.bind(this, record)}>设为默认</a>):null}
                            {record.status === 1?<a style={record.status === 2?{ marginLeft: '10px' }:{}} onClick={this.pass.bind(this, record)}>审核通过</a>:''}                            
                            {record.status === 1?<a style={{ marginLeft: '10px' }} onClick={this.showEdit.bind(this, record)}>审核驳回</a>:''}
                            {!record.defauls?<a style={{ marginLeft: '10px' }} onClick={this.deleteRow.bind(this, record)}>删除</a>:''}
                        </div>
                    )
                }
            },
        ];
        return (
            <div className="common-table" style={{ marginTop: '10px' }}>
                <Table title={(data) => { return '客户签名列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1900, y: this.state.tableHeight}}></Table>
                <Modal visible={this.state.showEditModal} onCancel={this.handleCancel.bind(this)} title="审核" footer={[
                    <Button key="sure" type="primary" onClick={this.handleSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="驳回原因" {...formItemLayout}>
                            {getFieldDecorator('reason', { validateFirst: true, rules: [{ required: true, message: '请输入原因' }, { max: 50, message: '50位以内' },Com.validateSpace] })(<TextArea rows={3} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div >
        )
    }
}

const ValidateTable = Form.create()(Table1);

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            loading: true,
            currentPage: 1,
            allAccount: [],
            app:[],
            industry:[]
        }
    }
    async componentWillMount(){
        await Com.getSelection.call(this, 'SmsUserSignApplicationEnum', 'app', false);
        await Com.getSelection.call(this, 'SmsUserSignIndustryEnum', 'industry',false);
    }
    setParams(obj, allAccount) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
            allAccount
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getUserSign'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    if(item.reason)
                    item.reasonAbb = Com.abbrData(item.reason,10);
                    this.state.app.forEach((item1)=>{
                        if(item1.index === item.application){
                            item.appName = item1.desc
                        }
                    })
                    this.state.industry.forEach((item1)=>{
                        if(item1.index === item.industry){
                            item.industryName = item1.desc
                        }
                    })
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    deleteRow(record) {
        let that = this;
        confirm({
            title: '删除',
            content: '您确定要删除吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['deleteSign'] + '?id=' + record.id).then(res => {
                    if (res) {
                        that.search();
                        message.success('删除成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    render() {
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <ValidateTable
                        search={this.search.bind(this)}
                        tableData={this.state.tableData}
                        dataNum={this.state.totalNum}
                        changePageSize={this.changePageSize.bind(this)}
                        changePage={this.changePage.bind(this)}
                        currentPage={this.state.currentPage}
                        deleteRow={this.deleteRow.bind(this)}
                        allAccount={this.state.allAccount}
                    />
                </Spin>
            </div>
        )
    }
}

export default Box